/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.app.modular.appuser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.app.core.consts.AppConstant;
import vip.xiaonuo.app.core.tx.TxIm;
import vip.xiaonuo.app.modular.appuser.enums.AppUserExceptionEnum;
import vip.xiaonuo.app.modular.appuser.param.front.ApiAppUserParam;
import vip.xiaonuo.app.modular.appuser.param.front.ApiGetUserPageParam;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.app.modular.appuser.entity.AppUser;
import vip.xiaonuo.app.modular.appuser.mapper.AppUserMapper;
import vip.xiaonuo.app.modular.appuser.param.mgr.AppUserParam;
import vip.xiaonuo.app.modular.appuser.service.AppUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * app用户表service接口实现类
 *
 * @author 郑雄伟
 * @date 2023-09-20 15:12:16
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
    @Resource
    private SysFileInfoService sysFileInfoService;

    @Override
    @Transactional
    public void updateUser(ApiAppUserParam param) {
        //根据id查询用户信息
        AppUser appUser = this.getById(param.getId());
        BeanUtil.copyProperties(param, appUser);
        //判断是否完善信息
        if (appUser.getIsComplete().equals(AppConstant.IS_COMPLETE_ONE)) {
            appUser.setIsComplete(AppConstant.IS_COMPLETE_ZERO);
        }
        //根据id更新数据库
        boolean b = this.updateById(appUser);
        //执行TxIm 昵称 或 头像 修改
        if (b) {
            //获取用户头衔
            String headPicUrl = sysFileInfoService.getSysFileInfo(appUser.getHeadPicId());
            //修改用户昵称
            TxIm.updateAccountSet(appUser.getTxCode(), appUser.getNick(), null);
            //修改用户头像
            TxIm.updateAccountSet(appUser.getTxCode(), null, headPicUrl);
        }
    }

    @Override
    public AppUser getUserByAccount(String loginName) {
        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUser::getLoginName, loginName);
        //忽略注销
        queryWrapper.ne(AppUser::getStatus, AppConstant.USER_STATUS_TWO);
        return this.getOne(queryWrapper);
    }


    @Override
    public void recordLastLogin(Long userId, String ipAddr, Date date) {
        baseMapper.recordLastLogin(userId, ipAddr, date);
    }

    @Override
    public boolean register(AppUser appUser) {
        return this.save(appUser);
    }

    @Override
    public PageResult<AppUser> getUserPage(ApiGetUserPageParam param) {

        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(param)) {
            //根据性别
            if (ObjectUtil.isNotEmpty(param.getSex())) {
                queryWrapper.eq(AppUser::getSex, param.getSex());
            }
            //根据账号类型
//            if (ObjectUtil.isNotEmpty(param.getIsReal())){
//                queryWrapper.eq(AppUser::getIsReal,param.getIsReal());
//            }


        }

        // 查询启用状态的
//            queryWrapper.eq(AppUser::getStatus, StatusConstant.USER_STATUS_ZERO);
        //根据排序升序排列，序号越小越在前
        queryWrapper.orderByDesc(AppUser::getCreateTime);
        //查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }



    @Override
    public AppUser getUserInfoTxCode(String txCode) {
        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUser::getTxCode, txCode);
        return this.getOne(queryWrapper);
    }


    @Override
    public PageResult<AppUser> page(AppUserParam appUserParam) {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(appUserParam)) {

            // 根据登录名称 即为：手机号 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLoginName())) {
                queryWrapper.lambda().eq(AppUser::getLoginName, appUserParam.getLoginName());
            }
            // 根据密码 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getPassWord())) {
                queryWrapper.lambda().eq(AppUser::getPassWord, appUserParam.getPassWord());
            }
            // 根据用户唯一编码 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getUserCode())) {
                queryWrapper.lambda().eq(AppUser::getUserCode, appUserParam.getUserCode());
            }
            // 根据身份唯一邀请码 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getInviteCode())) {
                queryWrapper.lambda().eq(AppUser::getInviteCode, appUserParam.getInviteCode());
            }
            // 根据腾讯生成编码ID 9位 IM使用 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getTxCode())) {
                queryWrapper.lambda().eq(AppUser::getTxCode, appUserParam.getTxCode());
            }
            // 根据是否完善过基础信息   1已完善  2 未完善 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getIsComplete())) {
                queryWrapper.lambda().eq(AppUser::getIsComplete, appUserParam.getIsComplete());
            }
            // 根据头像id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getHeadPicId())) {
                queryWrapper.lambda().eq(AppUser::getHeadPicId, appUserParam.getHeadPicId());
            }
            // 根据昵称 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getNick())) {
                queryWrapper.lambda().eq(AppUser::getNick, appUserParam.getNick());
            }
            // 根据性别：1男 2女 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getSex())) {
                queryWrapper.lambda().eq(AppUser::getSex, appUserParam.getSex());
            }
            // 根据签名 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getSign())) {
                queryWrapper.lambda().eq(AppUser::getSign, appUserParam.getSign());
            }
            // 根据生日 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getBirthday())) {
                queryWrapper.lambda().eq(AppUser::getBirthday, appUserParam.getBirthday());
            }
            // 根据身高id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getHeightId())) {
                queryWrapper.lambda().eq(AppUser::getHeightId, appUserParam.getHeightId());
            }
            // 根据体重id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getWeightId())) {
                queryWrapper.lambda().eq(AppUser::getWeightId, appUserParam.getWeightId());
            }
            // 根据职业id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getCareerId())) {
                queryWrapper.lambda().eq(AppUser::getCareerId, appUserParam.getCareerId());
            }
            // 根据收入id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getIncomeId())) {
                queryWrapper.lambda().eq(AppUser::getIncomeId, appUserParam.getIncomeId());
            }
            // 根据标签id 数组 英文逗号隔开 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getTagIds())) {
                queryWrapper.lambda().eq(AppUser::getTagIds, appUserParam.getTagIds());
            }
            // 根据学历id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getEducId())) {
                queryWrapper.lambda().eq(AppUser::getEducId, appUserParam.getEducId());
            }
            // 根据省份id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getPrId())) {
                queryWrapper.lambda().eq(AppUser::getPrId, appUserParam.getPrId());
            }
            // 根据城市id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getCityId())) {
                queryWrapper.lambda().eq(AppUser::getCityId, appUserParam.getCityId());
            }
            // 根据区id 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getDistId())) {
                queryWrapper.lambda().eq(AppUser::getDistId, appUserParam.getDistId());
            }
            // 根据形象id 数组 英文逗号隔开 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getIntroPicIds())) {
                queryWrapper.lambda().eq(AppUser::getIntroPicIds, appUserParam.getIntroPicIds());
            }
            // 根据经度 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLon())) {
                queryWrapper.lambda().eq(AppUser::getLon, appUserParam.getLon());
            }
            // 根据维度 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLat())) {
                queryWrapper.lambda().eq(AppUser::getLat, appUserParam.getLat());
            }
            // 根据状态（字典 0正常 1冻结 2删除） 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getStatus())) {
                queryWrapper.lambda().eq(AppUser::getStatus, appUserParam.getStatus());
            }
            // 根据登录次数 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLoginNum())) {
                queryWrapper.lambda().eq(AppUser::getLoginNum, appUserParam.getLoginNum());
            }
            // 根据最后登陆IP 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLastLoginIp())) {
                queryWrapper.lambda().eq(AppUser::getLastLoginIp, appUserParam.getLastLoginIp());
            }
            // 根据最后登陆时间 查询
            if (ObjectUtil.isNotEmpty(appUserParam.getLastLoginTime())) {
                queryWrapper.lambda().eq(AppUser::getLastLoginTime, appUserParam.getLastLoginTime());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<AppUser> list(AppUserParam appUserParam) {
        return this.list();
    }

    @Override
    public void add(AppUserParam appUserParam) {
        AppUser appUser = new AppUser();
        BeanUtil.copyProperties(appUserParam, appUser);
        this.save(appUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<AppUserParam> appUserParamList) {
        appUserParamList.forEach(appUserParam -> {
            this.removeById(appUserParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AppUserParam appUserParam) {
        AppUser appUser = this.queryAppUser(appUserParam);
        BeanUtil.copyProperties(appUserParam, appUser);
        this.updateById(appUser);
    }

    @Override
    public AppUser detail(AppUserParam appUserParam) {
        return this.queryAppUser(appUserParam);
    }

    /**
     * 获取app用户表
     *
     * @author 郑雄伟
     * @date 2023-09-20 15:12:16
     */
    private AppUser queryAppUser(AppUserParam appUserParam) {
        AppUser appUser = this.getById(appUserParam.getId());
        if (ObjectUtil.isNull(appUser)) {
            throw new ServiceException(AppUserExceptionEnum.NOT_EXIST);
        }
        return appUser;
    }

    @Override
    public void export(AppUserParam appUserParam) {
        List<AppUser> list = this.list(appUserParam);
        PoiUtil.exportExcelWithStream("SnowyAppUser.xls", AppUser.class, list);
    }

}
